import React from 'react';
import {Form,Input,Button} from 'antd'
import service from '../../api'
import "./Login.scss"
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom';
import { notification } from 'antd'

interface Props {}

function Login(props:Props) {
    
    var dispatch = useDispatch()
    var navigate = useNavigate();

    //表单验证通过时, 执行  
    const onFinish = async (values: any) => {
        console.log('Success:', values);
        //发起登陆请求
        var res = await service.admin.admin_login( values )
        
        notification.destroy();
        if( res.data.code == 200 ){
            //弹出通知框
            notification.success({message:'登陆成功!'});
            //保存用户信息
            dispatch({ type:'SAVE_USERINFO',payload: res.data.data })
            //跳转到首页
            navigate('/index');
        }else{
            notification.error({message:'登陆失败!'});
        }
    };

    //用户名的验证器
    var adminnameValidator = (rule:any, value:any, callback:any) => {
        // if( /^1[3-9]\d{9}$/.test( value ) || value == 'admin' ){
        if( value && value.length < 7  ){
            callback();
        }else{
            callback(new Error('请输入登陆账号!'));
        }
    }
    //密码的验证器
    var passwordValidator = (rule:any, value:any, callback:any) => {
        if( /^\d{6}$/.test( value ) ){
            callback();
        }else{
            callback(new Error('请输入符合格式的密码!'));
        }
    }

    return (
        <div className='login'>
            <div className="title">嗨购后台管理系统</div>
            <Form
                className='form'
                style={{ minWidth: 360 }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item
                name="adminname"
                rules={[{ validator: adminnameValidator }]}
                >
                    <Input placeholder='默认账号: admin' />
                </Form.Item>

                <Form.Item
                name="password"
                rules={[{ validator: passwordValidator }]}
                >
                    <Input.Password  placeholder='默认密码: 123456'/>
                </Form.Item>

                <Form.Item>
                    <Button block type="primary" htmlType="submit">
                        登陆
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}

export default Login;